<template>
	<view class="profile-page">
		<!-- 顶部渐变背景和大头像 -->
		<view class="header-bg">
			<view class="avatar-box" @click="chooseAvatar">
				<image :src="avatarDisplayUrl" class="avatar-img" />
				<view class="avatar-upload">
					<u-icon name="camera" size="36" color="#fff" />
				</view>
			</view>
			<view class="user-info">
				<view class="nickname-row">
					<text class="nickname">{{ user.nickname || '未设置昵称' }}</text>
					<u-tag v-if="user.isVip" text="会员" type="warning" size="mini" class="vip-tag" />
				</view>
				<view class="phone">{{ user.phone ? formatPhone(user.phone) : '未绑定手机号' }}</view>
			</view>
		</view>

		<!-- 信息项卡片 -->
		<view class="info-card">
			<view class="info-list">
				<view class="info-item">
					<view class="info-label">昵称</view>
					<u-input v-model="user.nickname" placeholder="请输入昵称" maxlength="16" border="none" clearable />
				</view>
				<view class="info-item">
					<view class="info-label">性别</view>
					<div class="gender-radio">
						<div class="radio-item" :class="{ active: user.gender === '1' }" @click="user.gender = '1'">
							<view class="radio-circle">
								<view v-if="user.gender === '1'" class="radio-dot"></view>
							</view>
							<text class="gender-text">男</text>
						</div>
						<div class="radio-item" :class="{ active: user.gender === '2' }" @click="user.gender = '2'">
							<view class="radio-circle">
								<view v-if="user.gender === '2'" class="radio-dot"></view>
							</view>
							<text class="gender-text">女</text>
						</div>
						<div class="radio-item" :class="{ active: user.gender === '0' }" @click="user.gender = '0'">
							<view class="radio-circle">
								<view v-if="user.gender === '0'" class="radio-dot"></view>
							</view>
							<text class="gender-text">未知</text>
						</div>
					</div>
				</view>
				<view class="info-item">
					<view class="info-label">生日</view>
					<picker mode="date" :value="user.birthdaytimeFormat" @change="onBirthdayChange">
						<view class="info-value">{{ user.birthdaytimeFormat || '请选择生日' }}</view>
					</picker>
				</view>
				<view class="info-item">
					<view class="info-label">手机号</view>
					<u-input v-model="user.phone" placeholder="请输入手机号" maxlength="11" type="number" border="none" clearable />
				</view>
				<view class="info-item">
					<view class="info-label">个性签名</view>
					<u-input v-model="user.signature" placeholder="请输入个性签名" maxlength="32" border="none" clearable />
				</view>
			</view>
		</view>

		<!-- 底部操作区 -->
		<view class="bottom-actions">
			<u-button type="primary" shape="circle" @click="saveAll">保存</u-button>
			<u-button type="error" shape="circle" plain @click="showLogoutConfirm = true">注销账户</u-button>
		</view>

		<!-- 注销确认弹窗 -->
		<u-modal
			v-model="showLogoutConfirm"
			title="注销账户"
			content="注销后将清空所有数据且无法恢复，确定要注销吗？"
			showCancel="取消"
			confirmText="确定注销"
			@confirm="handleLogout"
			:mask-close-able="true"
		/>
	</view>
</template>

<script>
import request from '@/common/request.js';
import { mapState, mapActions } from 'vuex';
import { checkLoginStatus, getUserInfo, wechatMiniLogin, fetchUserInfo, fetchUserBalance, fetchUserVouchers, logout } from '@/common/auth.js';

export default {
	data() {
		return {
			user: {
				image: '',
				nickname: '',
				gender: '',
				phone: '',
				birthdaytime: '',
				birthdaytimeFormat: '',
				signature: '',
				isVip: false
			},
			defaultAvatar: 'https://cdn.uviewui.com/uview/album/1.jpg',
			pickerValue: '',
			showLogoutConfirm: false
		};
	},
	computed: {
		...mapState({
			storeUserInfo: (state) => state.userInfo,
			globalConfig: (state) => state.config
		}),
		avatarDisplayUrl() {
			if (!this.user.image) {
				return '/static/default-avatar.png'; // 默认头像
			}
			// 如果是本地临时文件路径，直接显示
			if (this.user.image.startsWith('http://tmp/') || this.user.image.startsWith('wxfile://')) {
				return this.user.image;
			}
			// 如果已经是完整的URL，直接返回
			if (this.user.image.startsWith('http') || this.user.image.startsWith('//')) {
				return this.user.image;
			}
			// 如果是相对路径，并且全局配置已加载，则拼接
			if (this.globalConfig && this.globalConfig.site_url) {
				return this.globalConfig.site_url + this.user.image;
			}
			// 降级处理，或在配置加载前临时显示
			return '';
		}
	},
	onShow() {
		this.loadInitialData();
	},
	onLoad() {},
	methods: {
		...mapActions(['updateUserInfo', 'logout']),
		async loadInitialData() {
			// 确保全局配置已加载
			if (!this.globalConfig || !this.globalConfig.site_url) {
				try {
					await this.$store.dispatch('fetchConfig');
				} catch (error) {
					this.$u.toast('加载全局配置失败');
				}
			}
			// 加载用户数据
			await this.loadUserData();
		},
		// 加载用户数据
		async loadUserData() {
			const res = await fetchUserInfo();
			this.userInfo = res.user_info;
			console.log(this.userInfo, 'userInfo');
			if (this.userInfo) {
				this.user = {
					image: this.userInfo.image || '',
					nickname: this.userInfo.nickname || '',
					gender: this.userInfo.gender || '',
					phone: this.userInfo.phone || '',
					birthdaytime: this.userInfo.birthdaytime || '',
					birthdaytimeFormat: this.userInfo.birthdaytime ? this.formatDate(this.userInfo.birthdaytime) : '',
					signature: this.userInfo.signature || '',
					isVip: this.userInfo.isVip || false
				};
			}
		},
		// 头像选择
		chooseAvatar() {
			uni.chooseImage({
				count: 1,
				sourceType: ['album', 'camera'],
				sizeType: ['compressed'],
				success: (res) => {
					console.log('图片选择成功:', res);
					if (res.tempFilePaths && res.tempFilePaths.length > 0) {
						const tempPath = res.tempFilePaths[0];
						this.user.image = tempPath; // 立即回显本地图片
						this.uploadAvatar(tempPath);
					} else {
						console.error('未找到选择的图片路径', res);
						this.$u.toast('获取图片路径失败');
					}
				},
				fail: (err) => {
					console.error('图片选择失败:', err);
					this.$u.toast('选择图片失败');
				}
			});
		},
		// 上传头像
		async uploadAvatar(filePath) {
			console.log('准备上传的文件路径:', filePath);
			uni.showLoading({
				title: '上传中...'
			});
			try {
				// 步骤1: 使用 uni.uploadFile 上传文件
				const uploadResult = await new Promise((resolve, reject) => {
					uni.uploadFile({
						url: request.baseUrl + '/api/user/upload',
						filePath: filePath,
						name: 'file',
						header: {
							token: uni.getStorageSync('token')
						},
						success: (uploadRes) => {
							const data = JSON.parse(uploadRes.data);
							if (uploadRes.statusCode === 200 && data.code === 1) {
								resolve(data);
							} else {
								reject(new Error(data.msg || '服务器上传失败'));
							}
						},
						fail: (err) => {
							console.log(err);
							reject(new Error('网络请求失败，请检查网络连接'));
						}
					});
				});

				const avatarUrl = uploadResult.data.url;
				console.log('图片上传成功，URL:', avatarUrl);

				// 步骤2: 调用更新接口
				const updateResult = await request.httpTokenRequest({
					url: '/api/user/update',
					method: 'post',
					data: { image: avatarUrl }
				});

				if (updateResult.data.code !== 1) {
					throw new Error(updateResult.data.msg || '更新用户信息失败');
				}

				// 步骤3: 直接更新本地和全局状态，不再重新请求
				this.user.image = avatarUrl; // 更新本页面的数据
				this.updateUserInfo({ image: avatarUrl }); // 更新Vuex中的全局数据
				this.$u.toast('头像更新成功');
			} catch (error) {
				// 如果任何步骤失败，则重新加载一次服务器的数据，恢复到上传前的状态
				this.loadUserData();
				this.$u.toast(error.message || '操作失败');
			} finally {
				uni.hideLoading();
			}
		},
		// 手机号格式化
		formatPhone(phone) {
			if (!phone) return '';
			return phone.substr(0, 3) + '****' + phone.substr(7);
		},
		// 生日选择确认
		onBirthdayChange(e) {
			const dateStr = e.detail.value;
			const timestamp = new Date(dateStr.replace(/-/g, '/')).getTime() / 1000;
			this.user.birthdaytime = timestamp;
			this.user.birthdaytimeFormat = this.formatDate(timestamp);
		},
		// 保存全部
		async saveAll() {
			uni.showLoading({
				title: '保存中...'
			});
			try {
				const params = {
					nickname: this.user.nickname,
					gender: this.user.gender,
					birthdaytime: this.user.birthdaytime,
					signature: this.user.signature,
					phone: this.user.phone,
					image: this.user.image
				};

				const res = await request.httpTokenRequest({
					url: '/api/user/updateUserInfo', // Use consistent endpoint
					method: 'post',
					data: params
				});

				if (res.data.code === 1) {
					this.$u.toast('保存成功');
					await this.loadUserData(); // Refresh data
					setTimeout(() => {
						uni.navigateBack();
					}, 1000);
				} else {
					throw new Error(res.data.msg || '保存失败');
				}
			} catch (error) {
				this.$u.toast(error.message || '操作失败');
			} finally {
				uni.hideLoading();
			}
		},
		// 注销账户
		async handleLogout() {
			this.showLogoutConfirm = false;
			try {
				const opts = {
					url: '/api/user/logOff',
					method: 'post'
				};
				const res = await request.httpTokenRequest(opts);
				if (res.data.code == 1) {
					await this.logout();
					this.$u.toast('账户已注销');
					setTimeout(() => {
						uni.reLaunch({ url: '/pages/index/tabbar' });
					}, 1500);
				} else {
					throw new Error(res.msg || '注销失败');
				}
			} catch (error) {
				this.$u.toast(error.message || '注销失败');
			}
		},
		formatDate(ts) {
			if (!ts) return '';
			const date = new Date(ts.toString().length === 10 ? ts * 1000 : ts);
			const y = date.getFullYear();
			const m = (date.getMonth() + 1).toString().padStart(2, '0');
			const d = date.getDate().toString().padStart(2, '0');
			return `${y}-${m}-${d}`;
		}
	}
};
</script>

<style lang="scss">
.profile-page {
	min-height: 100vh;
	background: #f5f7fa;

	.header-bg {
		background: linear-gradient(180deg, #5a9cf8 0%, #b2d2ff 100%);
		padding-bottom: 60rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		position: relative;

		.avatar-box {
			position: relative;
			width: 160rpx;
			height: 160rpx;
			border-radius: 50%;
			overflow: hidden;
			margin-top: 60rpx;
			box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);

			.avatar-img {
				width: 100%;
				height: 100%;
			}

			.avatar-upload {
				position: absolute;
				right: 0;
				bottom: 0;
				background: rgba(0, 0, 0, 0.4);
				border-radius: 50%;
				padding: 8rpx;
			}
		}

		.user-info {
			margin-top: 24rpx;
			display: flex;
			flex-direction: column;
			align-items: center;

			.nickname-row {
				display: flex;
				align-items: center;

				.nickname {
					font-size: 36rpx;
					font-weight: bold;
					color: #fff;
				}

				.vip-tag {
					margin-left: 16rpx;
				}
			}

			.phone {
				margin-top: 8rpx;
				color: #e6e6e6;
				font-size: 26rpx;
			}
		}
	}

	.info-card {
		margin: -40rpx 24rpx 0 24rpx;
		border-radius: 24rpx;
		box-shadow: 0 4rpx 24rpx rgba(90, 156, 248, 0.08);
		background: #fff;
		padding: 24rpx;
		position: relative;
	}

	.info-list {
		display: flex;
		flex-direction: column;
	}

	.info-item {
		display: flex;
		align-items: center;
		padding: 32rpx 0 32rpx 0;
		position: relative;

		.info-label {
			flex: 0 0 160rpx;
			color: #333;
			font-size: 30rpx;
		}

		.info-value {
			flex: 1;
			margin-left: 16rpx;
			color: #666;
			font-size: 30rpx;
		}
	}

	.bottom-actions {
		margin: 48rpx 24rpx 0 24rpx;
		display: flex;
		flex-direction: column;
		gap: 24rpx;

		.u-button {
			font-size: 30rpx;
		}
	}

	.date-picker-mask {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.3);
		z-index: 9999;
		display: flex;
		align-items: flex-end;
		justify-content: center;
	}

	.date-picker-popup {
		background: #fff;
		border-radius: 24rpx 24rpx 0 0;
		width: 100%;
		padding: 40rpx 32rpx 32rpx 32rpx;
	}

	.picker-inner {
		text-align: center;
		font-size: 32rpx;
		padding: 32rpx 0;
	}

	.picker-btns {
		display: flex;
		justify-content: flex-end;
		margin-top: 24rpx;
	}
}

.gender-radio {
	display: flex;
	justify-content: flex-start;
	align-items: center;
	gap: 40rpx;
	margin-left: 16rpx;
}

.radio-item {
	display: flex;
	align-items: center;
	cursor: pointer;
	padding: 0 8rpx;
	border: none;
	background: transparent;
}

.radio-circle {
	width: 32rpx;
	height: 32rpx;
	border-radius: 50%;
	border: 2rpx solid #c0c0c0;
	background: #fff;
	margin-right: 10rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	transition: border-color 0.2s;
}

.radio-item.active .radio-circle {
	border-color: #5a9cf8;
}

.radio-dot {
	width: 16rpx;
	height: 16rpx;
	border-radius: 50%;
	background: #5a9cf8;
}

.gender-text {
	font-size: 28rpx;
	color: #666;
}

.radio-item.active .gender-text {
	color: #2468f2;
	font-weight: bold;
}
</style>
